package org.psyduck.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.psyduck.common.model.JsonBean;
import org.psyduck.common.model.PageJsonBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.adapter.Resource;
import org.ssssssss.magicapi.adapter.resource.DatabaseResource;
import org.ssssssss.magicapi.config.MagicDynamicDataSource;
import org.ssssssss.magicapi.model.PageResult;
import org.ssssssss.magicapi.provider.ResultProvider;

import javax.sql.DataSource;

@Configuration
public class MagicApiConfig {

    @Bean
    public MagicDynamicDataSource magicDynamicDataSource(DataSource dataSource) {
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;
        MagicDynamicDataSource ds = new MagicDynamicDataSource();
        ds.setDefault(dynamicRoutingDataSource.getDataSource("master"));
//        ds.put("slave",dynamicRoutingDataSource.getDataSource("slave"));
        return ds;
    }

    @Bean
    public Resource databaseResource(MagicDynamicDataSource dataSource) {
        return new DatabaseResource(dataSource.getDataSource().getJdbcTemplate(), "magic_api_file");
    }

    @Bean
    public ResultProvider resultProvider() {
        return (requestEntity, code, message, data) -> {
            if (data instanceof PageResult) {
                PageResult<Object> result = (PageResult<Object>) data;
                Page<Object> page = new Page<>();
                page.setTotal(result.getTotal());
                page.setRecords(result.getList());
                return PageJsonBean.success(page);
            }
            if (code == 1) {
                return JsonBean.success(data);
            }
            return new org.ssssssss.magicapi.model.JsonBean<>(code, message, data);
        };
    }


}
